package com.hubei.car.config;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.List;


/**
 * swagger2配置
 * @author luokangtao
 * @create 2019-07-15 17:19
 */
@Configuration  //@Configuration注解，表明它是一个配置类
@Data
public class Swagger2Config {

    @Value("${swagger2.title}")
    private String title;//头部
    @Value("${swagger2.description}")
    private String description;//描述
    @Value("${swagger2.version}")
    private  String version;//版本号
    @Value("${swagger2.basePackage}")
    private String basePackage;//扫描的包
    @Value("${swagger2.contact}")
    private String contact;//作者

    @Bean
    public Docket controllerApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                //apiINfo()配置一些基本的信息。
                .apiInfo(new ApiInfoBuilder()
                        // 设置页面标题
                        .title(title)
                        //描述
                        .description(description)
                        //定义版本号
                        .version(version)
                        //作者
                        .contact(contact)
                        .build())
                .select()
                //apis()指定扫描的包会生成文档。
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                //添加头部token
                .globalOperationParameters(setHeaderToken());
    }

    /**
     * 添加头部token
     * @return
     */
    private List<Parameter> setHeaderToken() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        tokenPar.name("Authorization").description("Access Token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        List<Parameter> pars = new ArrayList<>();
        pars.add(tokenPar.build());
        return pars;
    }
}
